package com.example.langchain4j.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 生成文件访问接口
 * 用于前端访问和下载生成的文档
 */
@RestController
@RequestMapping("/api/generated")
@Tag(name = "生成文件访问接口")
@Slf4j
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:5174", "http://localhost:5175"})
public class GeneratedFileController {

    private final Path fileStorageLocation;

    public GeneratedFileController() {
        // 使用相对于项目根目录的路径,明确指向backend目录
        Path mainPath = Paths.get("src/main/resources/generated").toAbsolutePath().normalize();

        this.fileStorageLocation = mainPath;
        log.info("GeneratedFileController: 文件存储路径 = {}", this.fileStorageLocation);

        // 确保目录存在
        try {
            if (!Files.exists(this.fileStorageLocation)) {
                Files.createDirectories(this.fileStorageLocation);
            }
        } catch (Exception e) {
            log.error("创建文件存储目录失败", e);
        }
    }

    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("GeneratedFileController is working");
    }

    /**
     * 下载文件
     */
    @GetMapping("/{fileName:.+}")
    @Operation(summary = "下载生成的文件")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists()) {
                // 根据文件扩展名确定正确的MIME类型
                MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
                if (fileName.endsWith(".docx")) {
                    mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                } else if (fileName.endsWith(".doc")) {
                    mediaType = MediaType.parseMediaType("application/msword");
                }

                return ResponseEntity.ok()
                        .contentType(mediaType)
                        .header(HttpHeaders.CONTENT_DISPOSITION,
                                "attachment; filename*=UTF-8''" + URLEncoder.encode(resource.getFilename(), StandardCharsets.UTF_8))
                        .body(resource);
            } else {
                log.warn("文件不存在: {}", filePath);
                return ResponseEntity.notFound().build();
            }
        } catch (Exception ex) {
            log.error("下载文件失败: {}", ex.getMessage(), ex);
            return ResponseEntity.internalServerError().build();
        }
    }
}
